<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/27
 * Time: 9:20
 */

namespace app\index\controller;


use think\Exception;
use think\Request;

class User extends Backend
{
    /**
     * 用户列表
     */
    public function index(){
        $data=Request::instance()->get();
        $model=db('user');
        if(isset($data['status']) && $data['status']!=''){
            $model->where(['user.status'=>$data['status']]);
        }
        if(isset($data['start_time']) && $data['start_time']!=''){
            $model->where(['user.created_time'=>['>=',strtotime($data['start_time'])]]);
        }
        if(isset($data['end_time']) && $data['end_time']!=''){
            $model->where(['user.created_time'=>['<=',strtotime($data['end_time'])+24*3600]]);
        }
        if(isset($data['username']) && $data['username']!=''){
            $model->where(['user.username'=>['like',"%{$data['username']}%"]]);
        }
        if(isset($data['mobile']) && $data['mobile']!=''){
            $model->where(['user.mobile'=>['like',"%{$data['mobile']}%"]]);
        }
        $list=$model->where(['status'=>['neq',2]])->order('user.created_time desc')
            ->paginate(20)
            ->each(function($item, $key){
                if($item['store_id']) {
                    $li = db('store')->where(['store_id' => $item['store_id']])
                        ->join('province p', 'store.province=p.province_id', 'left')
                        ->join('city c', 'store.city=c.city_id', 'left')
                        ->join('county y', 'store.area=y.county_id', 'left')
                        ->field('store.store_name,store.addres,p.province ,c.city ,y.county')
                        ->find();

                    $item['store_name'] = $li['store_name'];
                    $item['province'] = $li['province'];
                    $item['city'] = $li['city'];
                    $item['area'] = $li['county'];
                    $item['addres'] = $li['addres'];
                    return $item;
                }else{
                    $item['store_name'] = '';
                    $item['province'] ='';
                    $item['city'] ='';
                    $item['area'] = '';
                    $item['addres'] = '';
                    return $item;
                }
            });

        $this->assign('list', $list);

        return $this->fetch('index',['list'=>$list,'data'=>$data]);
    }
    /**
     * 修改
     */
    public function edit($user_id=0)
    {
        if ($data = Request::instance()->post()) {

            $user = [
                'username' => $data['username'],
                'sex' => $data['sex'],
                'store_id' => $data['store_id'],
                'number' => $data['number'],
                'avatar' => $data['logo'],
                'email' => $data['email'],
            ];

            $res = db('user')->where(['user_id' => $data['user_id']])->update($user);
            if ($res !== false) {
                return json_data([], 200, '编辑成功');
            }
            return json_data([], 300, '编辑失败');
        }else{
            if(!$user_id){
                $this->error('请刷新后重试');
            }
            $data=db('user')->where(['user_id'=>$user_id,])->find();
            $store=db('store')->select();
            if(!$data){
                $this->error('用户不存在或已删除');
            }
            return $this->fetch('edit',['data'=>$data,'store'=>$store]);
        }
    }
    /**
     * 删除用户
     */
    public function del(){
        $user_id=Request::instance()->post('user_id');
        $res=false;
        if($user_id){
            $res=db('user')->where(['user_id'=>$user_id])->delete();
        }
        if($res){
            return json_data([],200,'删除成功');
        }
        return json_data([],300,'删除失败');
    }
    /**
     * 启用 禁用
     */
    public function disable(){
        $user_id=Request::instance()->post('user_id');
        $status=Request::instance()->post('status');
        $res=db('user')->where(['user_id'=>$user_id])->value('store_id');
        if($res==0){
            $this->result([],300,'请分配账号后，在启用');
        }
        if($user_id && ($status==0 || $status==1)){
            $res=db('user')->where(['user_id'=>$user_id])->update(['status'=>$status]);
            if($res!==false){
                $this->result([],200,'操作成功');
            }
        }
        $this->result([],300,'请刷新后重试');
    }
    /**
     * c储备店长
     */
    public function she(){
        $user_id=Request::instance()->post('user_id');
        $status=Request::instance()->post('status');
        $res=db('user')->where(['user_id'=>$user_id])->value('store_id');
        if($res==0){
            $this->result([],300,'请分配账号后，在启用');
        }
        if($user_id && ($status==1 || $status==2)){
            $res=db('user')->where(['user_id'=>$user_id])->update(['reserve'=>$status]);
            if($res!==false){
                $this->result([],200,'操作成功');
            }
        }
        $this->result([],300,'请刷新后重试');
    }
    /**
     * 启用 禁用
     */
    public function qi(){
        $user_id=Request::instance()->post('user_id');
        $status=Request::instance()->post('status');

        if($user_id && ($status==0 || $status==1)){
            $res=db('user')->where(['user_id'=>$user_id])->update(['state'=>$status]);
            if($res!==false){
                $this->result([],200,'操作成功');
            }
        }
        $this->result([],300,'请刷新后重试');
    }

    /**
     * 重置密码
     */
    public function reset(){
        $user_id=Request::instance()->post('user_id');
        if(!$user_id){
            $this->result([],300,'请刷新后重试');
        }
        $res=db('user')->where(['user_id'=>$user_id])->update(['password'=>encrypt('123456')]);
        if($res!==false){
            return json_data([],200,'密码已重置为：123456');
        }
        return json_data([],300,'密码重置失败');
    }
    /**
     * 重置密码
     */
    public function cha($user_id){

        if(!$user_id){
            $this->result([],300,'请刷新后重试');
        }
        $res=db('user')->where(['user_id'=>$user_id])->find();
        if(empty($res['lat'])){
            return json_data([],300,'暂无地理数据');
        }
        return json_data(['id'=>$user_id],200,'');


    }
    public function map($user_id){


        $res=db('user')->where(['user_id'=>$user_id])->find();

        return $this->fetch('map',['admin'=>$res]);

    }
    /**
     * 修改管理员资料
     */
    public function edit_password(){
        $admin=$this->admin;
        if($post=Request::instance()->post()){
            if(!isset($post['logo']) || !$post['logo']){
                $this->result([],300,'请选择头像');
            }
            if($admin['password']!=encrypt($post['password'])){
                $this->result([],300,'原密码错误');
            }
            $update=[
                'access_token'=>'',
                'username'=>$post['username'],
                'logo'=>$post['logo']
            ];
            if(isset($post['new_password']) && $post['new_password']){
                if($post['new_password']!=$post['sure_password']){
                    $this->result([],300,'确认密码错误');
                }
                if(!is_password($post['new_password'])){
                    $this->result([],300,'请输入6~12位数字或字母为密码');
                }
                if($admin['password']==encrypt($post['new_password'])){
                    $this->result([],300,'新旧密码不能一样');
                }
                $update+=['password'=>encrypt($post['new_password'])];
            }

            $res=db('admin')
                ->where(['admin_id'=>$admin['admin_id']])
                ->update($update);
            if($res!==false){
                $this->result([],200,'修改成功');
            }
            $this->result([],300,'请刷新后重试');
        }
        return $this->fetch('',['admin'=>$admin]);
    }
    public function add(){
        $data=$this->post(['mobile','username','code','password','sex','age']);
        $data['avatar']="https://www.yiniaoweb.com/static/images/login/tx.png";
        if (!is_mobile($data['mobile'])) {
            res_date([], 300, '电话号码不符合规则');
        }
        if (!is_password($data['password'])) {
            res_date([], 300, '请输入6~12位数字或字母为密码');
        }
        $s_verify = Cache::get(md5($data['mobile']));
        if (empty($data['code']) || $data['code'] != $s_verify) {
            res_date([], 300, '验证码错误');

        }
        Cache::clear(md5($data['mobile']));
        $user = db("user")->where(['mobile'=>$data['mobile']])->find();
        if ($user) {
            if($user['status']!=3){
                res_date([], 300, '该手机号已经注册');
            }
        }
        $data['password']=encrypt($data['password']);
        $data['created_time']=time();
        $data['status']=1;
        unset($data['code']);
        \db()->startTrans();
        try {
            $user_id=\db("user")->insertGetId($data);
            \db()->commit();
            res_date(['user_id'=>$user_id], 200, '注册成功');
        } catch (Exception $e) {
            \db()->rollback();
            res_date([], 300, $e->getMessage());
        }
    }
}